package controllers

import (
	"strings"

	"github.com/gin-gonic/gin"
	common "jihe.common"
	"jihe.common/protos/auth_server"
	auth_server_proto "jihe.common/protos/auth_server/proto"
	"jihe.common/protos/user_server"
	user_server_proto "jihe.common/protos/user_server/proto"
	"jihe.common/protos/wx_server"
	"jihe.common/protos/wx_server/proto"
	wx_server_proto "jihe.common/protos/wx_server/proto"
	"jihe.common/resp"
)

type WxController struct {
	Redis common.Redis
}

func (s *WxController) DoAuthCode(c *gin.Context) {
	code := c.Query("code")
	if code == "" {
		resp.RespParamErr(c)
		return
	}
	ret, err := wx_server.WxCodeAuth(c, &proto.WxCodeAuthReq{
		Code: code,
	})
	if err != nil {
		common.Loger.Error("WxCodeAuth err:%v", err)
		resp.RespGeneralErr(c, "授权失败")
		return
	}
	userInfo, err := user_server.UserRegiste(c, &user_server_proto.UserDUser{
		Openid:  ret.Openid,
		Unionid: ret.Unionid,
	})
	if err != nil {
		if strings.Contains(err.Error(), "errorno=1") {
			resp.RespGeneralErr(c, "账号已被禁用")
			return
		}
		resp.RespGeneralErr(c, "注册失败")
		return
	}
	result, err := auth_server.CreateToken(c, &auth_server_proto.CreateTokenReq{
		Uid: userInfo.Id,
	})
	if err != nil {
		common.Loger.Error("CreateToken err:%v", err)
		resp.RespGeneralErr(c, "注册失败")
		return
	}
	retMap := make(map[string]interface{})
	retMap["secret"] = result
	retMap["uinfo"] = userInfo
	resp.RespOk(c, retMap)
}

func (s *WxController) UpdateInfo(c *gin.Context) {
	req := user_server_proto.UserDUser{}
	err := c.BindJSON(&req)
	if err != nil {
		resp.RespParamErr(c)
		return
	}
	req.Id = getUid(c)
	if req.Nickname == "" {
		resp.RespParamErr(c)
		return
	}
	_, err = user_server.UserUpdateInfo(c, &req)
	if err != nil {
		resp.RespGeneralErr(c)
		return
	}
	resp.RespOk(c)
}

func (s *WxController) UpdatePhone(c *gin.Context) {
	req := wx_server_proto.DecryptUserInfoReq{}
	err := c.BindJSON(&req)
	if err != nil {
		resp.RespParamErr(c)
		return
	}
	if req.EncryptedData == "" || req.Iv == "" || req.Openid == "" {
		resp.RespParamErr(c)
		return
	}
	user, err := wx_server.DecryptUserInfo(c, &req)
	if err != nil {
		common.Loger.Error("DecryptUserInfo err:%v", err)
		resp.RespGeneralErr(c)
		return
	}
	_, err = user_server.UserUpdatePhone(c, &user_server_proto.UserDUser{
		Id:    getUid(c),
		Phone: user.Phone,
	})
	if err != nil {
		resp.RespParamErr(c)
		return
	}
	resp.RespOk(c)
}
